package cn.iocoder.yudao.module.trade.service.stationinfo;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.CheckUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.infra.api.code.AutoCodeUtilsApi;
import cn.iocoder.yudao.module.infra.enums.SequenceRuleConstant;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.trade.controller.admin.deliverypickupstoreimage.vo.DeliveryPickUpStoreImageSaveReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.stationinfo.vo.StationInfoPageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.stationinfo.vo.StationInfoSaveReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.deliverypickupstoreimage.DeliveryPickUpStoreImageDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.stationinfo.StationInfoDO;
import cn.iocoder.yudao.module.trade.dal.mysql.deliverypickupstoreimage.DeliveryPickUpStoreImageMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.stationinfo.StationInfoMapper;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.STATION_INFO_NOT_EXISTS;

/**
 * 气站信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
public class StationInfoServiceImpl implements StationInfoService {
    private static final Log logger = LogFactory.getLog(StationInfoServiceImpl.class);
    @Resource
    private StationInfoMapper stationInfoMapper;
    @Resource
    private DeptApi deptApi;
    @Resource
    private DeliveryPickUpStoreImageMapper  deliveryPickUpStoreImageMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AutoCodeUtilsApi autoCodeUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createStationInfo(StationInfoSaveReqVO createReqVO) {
        // 插入部门表数据
        DeptRespDTO dto = new DeptRespDTO();
        dto.setName(createReqVO.getName());
        dto.setParentId(createReqVO.getDeptId());
        dto.setStatus(0);
        dto.setType(2);
        Long aLong = deptApi.saveDept(dto);

        // 插入
        StationInfoDO stationInfo = BeanUtils.toBean(createReqVO, StationInfoDO.class);
        // stationInfoCode 存于redis 手动在infra_code_increment表入库记录
        // 调用自动生成自增code工具类  格式： Q + 随机两位数 + 自增四位数
        stationInfo.setCode(autoCodeUtils.autoCode("stationInfoCode", new StringBuilder().append("Q").append(autoCodeUtils.random(2 )) ));
        stationInfo.setDeptId(aLong);
        stationInfoMapper.insert(stationInfo);

        //插入气站证件信息数据
        if (CollectionUtils.isNotEmpty(createReqVO.getImageList())){
            List<DeliveryPickUpStoreImageSaveReqVO> imageList = createReqVO.getImageList();
            imageList.forEach(x -> {
                x.setStoreId(stationInfo.getId());
            });
            deliveryPickUpStoreImageMapper.insertBatch(BeanUtils.toBean(imageList ,DeliveryPickUpStoreImageDO.class));
        }
        // 返回
        return stationInfo.getId();
    }

    @Override
    @Transactional
    public void updateStationInfo(StationInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateStationInfoExists(updateReqVO.getId());
        // 更新
        StationInfoDO updateObj = BeanUtils.toBean(updateReqVO, StationInfoDO.class);
        stationInfoMapper.updateById(updateObj);

        // 查询证件表数据
        LambdaQueryWrapperX<DeliveryPickUpStoreImageDO> wrapper = new LambdaQueryWrapperX<>();
        wrapper.eq(DeliveryPickUpStoreImageDO ::getStoreId, updateReqVO.getId() ).eq(DeliveryPickUpStoreImageDO ::getDeleted, 0 );
        List<DeliveryPickUpStoreImageDO> imageDOS = deliveryPickUpStoreImageMapper.selectList(wrapper);
        // 更新气站证件
        if (CollectionUtils.isNotEmpty(updateReqVO.getImageList())){

            List<Integer> imageAllId = imageDOS.stream().map(DeliveryPickUpStoreImageDO::getId).collect(Collectors.toList());
            // 实际需要更新的证件
            List<DeliveryPickUpStoreImageSaveReqVO> imageList = updateReqVO.getImageList();
            List<Integer> ids = imageList.stream().map(DeliveryPickUpStoreImageSaveReqVO::getId).collect(Collectors.toList());
            // 比较出需要删除的证件id
            List<Integer> diff = imageAllId.stream().filter(x -> !ids.contains(x)).collect(Collectors.toList());
            // 删除对应的证件
            if (CollectionUtils.isNotEmpty(diff)){
                deliveryPickUpStoreImageMapper.deleteBatchIds(diff);
            }


            imageList.forEach(x -> {
                x.setStoreId(updateReqVO.getId());
            });
            deliveryPickUpStoreImageMapper.insertOrUpdateBatch(BeanUtils.toBean(imageList, DeliveryPickUpStoreImageDO.class));
        } else {
            // 如果更新操作时删除所有的证件信息
            if (CollectionUtils.isNotEmpty(imageDOS)) {
                deliveryPickUpStoreImageMapper.deleteBatchIds(imageDOS.stream().map(DeliveryPickUpStoreImageDO::getId).collect(Collectors.toList()));
            }
        }

    }

    @Override
    public void deleteStationInfo(Long id) {
        // 校验存在
        validateStationInfoExists(id);
        // 删除
        stationInfoMapper.deleteById(id);
    }

    private void validateStationInfoExists(Long id) {
        if (stationInfoMapper.selectById(id) == null) {
            throw exception(STATION_INFO_NOT_EXISTS);
        }
    }

    @Override
    public StationInfoSaveReqVO getStationInfo(Long id) {
        // 查询气站信息数据
        StationInfoSaveReqVO stationInfoSaveReqVO = BeanUtils.toBean(stationInfoMapper.getStationInfoList(new StationInfoPageReqVO().setId(id)).get(0), StationInfoSaveReqVO.class);
        LambdaQueryWrapperX<DeliveryPickUpStoreImageDO> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.eq(DeliveryPickUpStoreImageDO::getStoreId, id);

        // 查询气站对应的证件信息
        List<DeliveryPickUpStoreImageDO> imageDOS = deliveryPickUpStoreImageMapper.selectList(wrapperX);
        stationInfoSaveReqVO.setImageList(CollectionUtils.isEmpty(imageDOS) ? null : BeanUtils.toBean(imageDOS, DeliveryPickUpStoreImageSaveReqVO.class));
        return stationInfoSaveReqVO;
    }

    @Override
    public PageResult<StationInfoPageReqVO> getStationInfoPage(StationInfoPageReqVO pageReqVO) {

        List<StationInfoPageReqVO> list = stationInfoMapper.getStationInfoList(pageReqVO);
        PageResult<StationInfoPageReqVO> result = new PageResult<>(list, (long) list.size());
//        return stationInfoMapper.selectPage(pageReqVO);
        return result;
    }

    @Override
    public List<StationInfoDO> getStationAllList() {
        return stationInfoMapper.selectList();
    }

}
